<template>
    <page-container title="面试安排">
        <template #extra>
            <el-input 
                v-model="search" 
                placeholder="请输入关键字" 
                style="width: 120px;height: 30px;margin-left: 50px;" 
                clearable
            />
            <el-button 
                style="margin-left: 30px; background-color: #5defc1; color: white" 
                @click="loadInterviews" 
                plain
            >查询</el-button>
        </template>

        <el-dialog
            v-model="feedbackDialogVisible"
            title="面试反馈"
            width="50%"
        >
            <el-form
                ref="feedbackFormRef"
                :model="feedbackForm"
                :rules="feedbackRules"
                label-width="150px"
            >
                <el-form-item label="专业技术评分" prop="professionalSkillsScore">
                    <el-rate
                        v-model="feedbackForm.professionalSkillsScore"
                        :max="5"
                        show-score
                    />
                </el-form-item>
                
                <el-form-item label="沟通技能评分" prop="communicationSkillsScore">
                    <el-rate
                        v-model="feedbackForm.communicationSkillsScore"
                        :max="5"
                        show-score
                    />
                </el-form-item>
                <el-form-item label="问题解决技能评分" prop="problemSolvingSkillsScore">
                    <el-rate
                        v-model="feedbackForm.problemSolvingSkillsScore"
                        :max="5"
                        show-score
                    />
                </el-form-item>
                <el-form-item label="总体评价" prop="overallEvaluation">
                    <el-input
                        v-model="feedbackForm.overallEvaluation"
                        type="textarea"
                        :rows="4"
                       placeholder="请输入总体评价"
                    />
                </el-form-item>
                <el-form-item label="录用建议" prop="hiringRecommendation">
                    <el-select v-model="feedbackForm.hiringRecommendation" placeholder="请选择录用建议">
                        <el-option label="录用" value="录用" />
                        <el-option label="备用" value="备用" />
                        <el-option label="不录用" value="不录用" />
                </el-select>
                </el-form-item>
            
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="feedbackDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitFeedback">
                        提交反馈
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <el-table 
            :data="interviews" 
            style="width: 100%" 
            v-loading="loading"
        >
            <el-table-column type="index" label="序号" fixed width="80"/>
            <el-table-column prop="candidateName" label="应聘者" width="150"/>
            <el-table-column prop="positionName" label="应聘职位" width="150"/>
            <el-table-column prop="name" label="面试官" width="150"/>
            <el-table-column prop="interviewTime" label="面试时间" width="150">
                <template #default="{ row }">
                    {{ formatDateTime(row.interviewTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="150">
                <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)">
                        {{ getStatusText(row.status)}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="150">
                <template #default="{ row }">
                    {{ formatDateTime(row.createTime) }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="150">
                <template #default="{ row }">
                    {{ formatDateTime(row.updateTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="300" fixed="right">
                <template #default="scope">
                    <el-button-group>
                        <el-button 
                            type="success" 
                            size="small"
                            @click="handleStatusChange(scope.row)"
                            :disabled="scope.row.status === 1"
                        >
                            录用
                        </el-button>
                        <el-button 
                            type="warning" 
                            size="small"
                            value="备用"
                            @click="handleSpare(scope.row)"
                            :disabled="scope.row.status === 2"
                        >
                            备用
                        </el-button>
                        <el-button 
                            type="danger" 
                            size="small"
                            @click="handleNoEmploy(scope.row)"
                            :disabled="scope.row.status === 3"
                        >
                            不录用
                        </el-button>
                        <el-button 
                            type="danger" 
                            size="small"
                            @click="handleDelete(scope.row)"
                        >
                            删除
                        </el-button>
                        <el-button 
                            type="primary" 
                            size="small"
                            @click="handleRecord(scope.row)"
                        >
                            记录
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>

        <template #pagination>
            <div class="demo-pagination-block">
                <el-pagination
                    v-show="total > 0"
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 40]"
                    :background="true"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </template>
    </page-container>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getInterviewList, updateInterviewStatus,deleteInterview,addInterviewFeedback,checkIsRecords } from '@/api/interview'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/PageContainer.vue'

const interviews = ref([])
const loading = ref(true)
const search = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const admin=JSON.parse(localStorage.getItem("admin"))
// 添加反馈相关的响应式变量
const feedbackDialogVisible = ref(false)
const feedbackFormRef = ref(null)
const currentInterview = ref(null)
const feedbackForm = ref({
    professionalSkillsScore: 0,
    communicationSkillsScore: 0,
    problemSolvingSkillsScore: 0,
    overallEvaluation: '',
    hiringRecommendation: '',
    interviewId: ''
})

const feedbackRules = {
    professionalSkillsScore: [
        { required: true, message: '请评分专业技术能力', trigger: 'change' }
    ],
    communicationSkillsScore: [
        { required: true, message: '请评分沟通技能', trigger: 'change' }
    ],
    problemSolvingSkillsScore: [
        { required: true, message: '请评分问题解决技能', trigger: 'change' }
    ],
    overallEvaluation: [
        { required: true, message: '请填写总体评价', trigger: 'blur' },
        { min: 10, message: '评价内容至少10个字符', trigger: 'blur' }
    ],
    hiringRecommendation: [
        { required: true, message: '请选择录用建议', trigger: 'change' }
    ]
}

// 获取面试列表
const loadInterviews = async () => {
    loading.value = true
    try {
        const res = await getInterviewList({
            current: currentPage.value,
            size: pageSize.value,
            search: search.value
        })
        console.log(res)
        if (res.code === 200) {
            interviews.value = res.data.records
            total.value = res.data.total
        } else {
            ElMessage.error('获取面试列表失败')
        }
    } catch (error) {
        console.error('获取面试列表失败：', error)
        ElMessage.error('获取面试列表失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 统一处理状态更新
const updateInterviewResult = async (row, status,confirmMessage) => {
    if(admin.role==="sub_admin" || admin.role==="super_admin"){
        try {
            await ElMessageBox.confirm(confirmMessage, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            const isRecords=await checkIsRecords(row.id)
        if(isRecords.data.feedbackId!=null){
                const res = await updateInterviewStatus({
                id: row.id,
                status:status
            })

            if (res.code === 200) {
                ElMessage.success('状态更新成功')
                await loadInterviews()
            } else {
                ElMessage.error(res.message || '状态更新失败')
            }
        }
        else {
            ElMessage.warning("请先填写面试反馈！")
        }
        
        } catch (error) {
            if (error !== 'cancel') {
                console.error('状态更新失败：', error)
                ElMessage.error('状态更新失败：' + error.message)
            }
        }
    }else{
        ElMessage.warning("您没有权限进行此操作")
    }
}

// 修改原有的处理方法
const handleStatusChange = (row) => {
    updateInterviewResult(row, 1,'确认录用此候选人？')
}

const handleSpare = (row) => {
    updateInterviewResult(row, 2,'确认将此候选人设为备用？')
}

const handleNoEmploy = (row) => {
    updateInterviewResult(row, 3,'确认不录用此候选人？')
}


const handleDelete = async (row) => {
    try {
        await ElMessageBox.confirm('确定要删除此面试信息吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const res = await deleteInterview(row.id)
        if (res.code === 200) {
            ElMessage.success('删除成功')
            loadInterviews()
        } else {
            ElMessage.error(res.message || '删除失败')
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败：', error)
            ElMessage.error('删除失败：' + error.message)
        }
    }
}

const handleRecord = (row) => {
  if(admin.role === 'admin' || admin.role === 'super_admin') {

    currentInterview.value = row
    feedbackForm.value = {
      professionalSkillsScore: 0,
      communicationSkillsScore: 0,
      problemSolvingSkillsScore: 0,
      overallEvaluation: '',
      hiringRecommendation: '',
      interviewId: row.id
    }
    feedbackDialogVisible.value = true
  }else{
    ElMessage.warning("您没有权限进行此操作")
  }
}

// 提交反馈
const submitFeedback = async () => {
    if (!feedbackFormRef.value) return
    
    await feedbackFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const res = await addInterviewFeedback(feedbackForm.value)
                console.log(res)
                if (res.code === 200) {
                    ElMessage.success('反馈提交成功')
                    feedbackDialogVisible.value = false
                    await loadInterviews()
                } else {
                    ElMessage.error(res.message || '提交失败')
                }
            } catch (error) {
                console.error('提交反馈失败：', error)
                ElMessage.error('提交反馈失败：' + error.message)
            }
        }
    })
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    loadInterviews()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    loadInterviews()
}

// 格式化日期
const formatDateTime = (dateStr) => {
    if (!dateStr) return '--'
    const date = new Date(dateStr)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    })
}

const getStatusType = (status) => {
    const statusMap = {
        0: 'info',  
        1: 'success' ,
        2: 'info',
        3: 'danger'
    }
    return statusMap[status] || 'info'
}

const getStatusText = (status) => {
    const statusMap = {
        0: '待面试',
        1: '通过面试',
        2: '待定',
        3: '未通过面试'
    }
    return statusMap[status] || '待面试'
}

onMounted(() => {
    loadInterviews()
})
</script>

<style scoped>
.demo-pagination-block {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.el-button-group {
    display: flex;
    gap: 8px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

:deep(.el-rate) {
    margin-top: 8px;
}

.el-radio-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.el-radio {
    margin-right: 0;
    padding: 8px 0;
}
</style>

